#include "../include/my_fs.hpp"
#include "../include/bambu.hpp"
#include "../include/my_ota.hpp"
#include "../include/my_wifi.hpp"
#include "../include/my_oled.hpp"
#include "../include/my_web.hpp"
#include "../include/motor.hpp"
#include "../include/debug_info.hpp"

TaskHandle_t Task4bambu;

static void Task_bambu( void * pvParameters ) {
  unsigned long previousMillis = 0;
  Serial.print("Task4bambu running on core ");
  Serial.println(xPortGetCoreID());
  for(;;){
    unsigned long currentMillis = millis();
    if(!bambu.Client->connected())
      bambu.ops->connect();
    bambu.Client->loop();
    if(currentMillis - previousMillis >= bambu.cfg->RenewTime){
      previousMillis = currentMillis;
      bambu.Client->publish(bambu.cfg->topic_publish.c_str(), bambu.comm->status.c_str());
    }
  }
}

static void bambuCallback(char* topic, byte* payload, unsigned int length) {
  bambu.ops->getdata(payload,length);
  bambu.ops->work();
}

void setup() {
  motor.ops->init();
  Serial.begin(115200);
  my_oled.ops->init();

  delay(10000);
  my_fs.ops->init();
  my_fs.ops->work();
  my_wifi.ops->connect();
  dbg.ops->init();
  my_oled.ops->showIP(my_wifi.cfg->ip);
  my_ota.ops->init();
  my_web.ops->init();
  bambu.cfg->callback = bambuCallback;
  xTaskCreatePinnedToCore(Task_bambu,"Task-bambu",4096,NULL,1,&Task4bambu,0);
  Serial.print("setup end!!\n");
}

void loop() {
  static uint32_t tickms;
  static uint32_t tick4Filament;
  my_ota.ops->loop();
  my_web.ops->loop();
  //dbg.ops->loop();
  if(tick4Filament + 5000 < millis() || tick4Filament > millis()){
    tick4Filament = millis();
    my_oled.ops->showFilament(String(bambu.data->lastFilament.toInt() + 1));
  }
}
